package javase.ch05.homeWork.Demo3;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.LockSupport;

/**
 * 广播消息给所有人
 */
public class ServerTasker implements Runnable{
    private Socket socket;
    private Thread currentThread;
    private CopyOnWriteArrayList<Socket> clients;
    BufferedReader br;
    PrintWriter pw;
    public ServerTasker(CopyOnWriteArrayList<Socket> clients, Socket socket, Thread currentThread){
        this.clients = clients;
        this.socket = socket;
        this.currentThread = currentThread;
    }
    @Override
    public void run() {

        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            String message;
            while((message=br.readLine())!=null){
                if(message.equals("886")){
                    for (Socket client : clients){
                        if(client != socket){
                           pw= new PrintWriter(client.getOutputStream());
                           pw.println(client.getRemoteSocketAddress() + "已下线");
                           pw.flush();
                        }
                        clients.remove(socket);
                        socket.close();
                    }
                }else {
                    for (Socket client : clients) {
                        if(client != socket){
                            pw = new PrintWriter(client.getOutputStream());
                            pw.println(client.getRemoteSocketAddress() + "说：" + message);
                            pw.flush();
                        }
                    }
                }

            }
        }catch (SocketException e){
            System.out.println("客户端异常退出");
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
            LockSupport.park(currentThread);
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
